package com.whahol.action;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.whahol.Utils;
import com.whahol.exception.ApplicationException;
import com.whahol.model.OAuthParams;

@Controller("authzController")
@RequestMapping("/")
public class AuthzController {

	private static String authzEndpoint;

	static {
		Properties p = new Properties();
		try {
			p.load(AuthzController.class.getClassLoader().getResourceAsStream(
					"config.properties"));
			authzEndpoint = p.getProperty("authzEndpoint");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("authorize")
	public ModelAndView authorize(
			@ModelAttribute("oauthParams") OAuthParams oauthParams,
			HttpServletRequest req, HttpServletResponse res)
			throws OAuthSystemException, IOException, OAuthProblemException {
		try {
			Utils.validateAuthorizationParams(oauthParams);
			OAuthClientRequest request = null;
			request = OAuthClientRequest.authorizationLocation(authzEndpoint)
					.setClientId(oauthParams.getClientId())
					.setRedirectURI(oauthParams.getRedirectUri())
					.setResponseType(oauthParams.getRequestType())
					.setParameter("scope", oauthParams.getScope())
					.setParameter("client_secret",oauthParams.getClientSecret())
					.setState(oauthParams.getState()).buildQueryMessage();
			return new ModelAndView(new RedirectView(request.getLocationUri()));
		} catch (ApplicationException e) {
			ModelAndView mav = new ModelAndView();
			mav.addObject("error", e.getMessage());
			mav.setViewName("error");
			return mav;
		}
	}

}
